# 导入:
# import mysql.connector.errorcode
import sqlalchemy
from sqlalchemy import Column, String, Integer, DateTime
from utils.sql.db import session, Base
import time
from utils.sql.public.location import phone_location

# import phonenumbers
# from phonenumbers import geocoder


# import tracemalloc


# 定义User对象:
class User(Base):
    # 表的名字:
    __tablename__ = 'user'

    # 表的结构:
    id = Column(Integer(), primary_key=True, default=None)
    user_id = Column(String(20))
    head_img = Column(String(255))
    nick_name = Column(String(20))
    user_name = Column(String(20), default='')
    phone_num = Column(String(20), default='')
    native_place = Column(String(20), default='')
    daily_wage = Column(Integer(), default=0)
    hourly_wage = Column(Integer(), default=0)
    day_manhour = Column(Integer(), default='8')
    job_location = Column(String(20), default='')
    ganger_id = Column(String(20), default='')
    level_num = Column(String(20), default='0')
    growth_num = Column(Integer(), default=0)
    share_id = Column(String(20), default='')
    create_time = Column(String(20), default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# 获取用户信息
def get_userinfo(user_id: str):
    user = None
    try:
        # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
        user = session.query(User).filter(User.user_id == user_id).one()
        if user:
            return {
                "code": 200,
                "data": user,
                "message": '查询成功'
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": "",
            "message": '查询失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# print(get_userinfo('ouWAN0S26fQ85AEDweRy_NDNf58M'))

# 添加用户
def insert_userinfo(data):
    # print(data, '11111111111111111')
    try:
        # 创建新User对象:
        new_user = User(
            user_id=data['id'],
            head_img=data['headimg'],
            nick_name=data['nickname'],
            share_id=data['share_id'],
            create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        )
        if data['share_id']:
            user = session.query(User).filter(User.user_id == data['share_id']).one()
            query = session.query(User).filter(User.user_id == data['share_id'])  # 添加合适的过滤条件
            level_num = '0'
            if float(user.growth_num) + 20 >= 500:
                level_num = '1'
            elif float(user.growth_num) + 20 >= 2000:
                level_num = '2'
            elif float(user.growth_num) + 20 >= 5000:
                level_num = '3'
            elif float(user.growth_num) + 20 >= 10000:
                level_num = '4'
            result = query.all()
            for item in result:
                # return
                # 将属性值设置为新的值
                # item.share_id = data['share_id']
                item.growth_num = float(user.growth_num) + 20
                item.level_num = level_num

        # 添加到session:
        session.add(new_user)
        # 提交即保存到数据库:
        session.commit()
        return {
            "code": 200,
            "data": "",
            "message": "数据添加成功"
        }
    except sqlalchemy.exc.IntegrityError as e:
        return {
            "code": 201,
            "data": e,
            "message": "数据已经存在"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# insert_userinfo()
# 验证数据库是否存在数据
def is_user(user_id: str):
    try:
        query = session.query(User).filter(User.user_id == user_id)
        is_exist = session.query(
            query.exists()
        ).scalar()
        # print(is_exist)
        if is_exist:
            print("数据存在")
            return {
                "code": 200,
                "data": is_exist,
                "message": "数据存在"
            }
        else:
            print("数据不存在")
            return {
                "code": 200,
                "data": is_exist,
                "message": "数据不存在"
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": e,
            "message": "数据查询失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# is_user('ouWAN0S26fQ85AEDweRy_NDNf58M')
# 更新用户信息
def update_info(data, user_id):
    # 查询要更新的记录
    try:
        query = session.query(User).filter(User.user_id == user_id)  # 添加合适的过滤条件
        result = query.all()
        # 获取手机号码归属地
        location = ''
        if data.phone_num:
            location = phone_location(data.phone_num)

        for item in result:
            # return
            # 将属性值设置为新的值
            item.user_name = data.user_name
            item.phone_num = data.phone_num
            item.day_manhour = data.day_manhour
            item.daily_wage = data.daily_wage
            item.hourly_wage = data.hourly_wage
            item.job_location = data.job_location
            item.native_place = location
        # 提交事务
        session.commit()
        return {
            "code": 200,
            "data": '',
            "message": "操作成功"
        }
    except sqlalchemy.exc.DBAPIError as e:
        return {
            "code": 201,
            "data": e,
            "message": "操作失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


